<?php

// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------


namespace app\controller\api;


use app\common\model\store\order\StoreOrderExpress;
use app\common\repositories\delivery\DeliveryOrderRepository;
use app\common\repositories\store\product\ProductAssistSetRepository;
use app\common\repositories\store\product\ProductGroupBuyingRepository;
use app\common\repositories\store\product\ProductGroupRepository;
use app\common\repositories\store\product\ProductPresellRepository;
use app\common\repositories\store\product\ProductRepository;
use app\common\repositories\store\shipping\ExpressRepository;
use app\common\repositories\store\StoreCategoryRepository;
use app\common\repositories\system\attachment\AttachmentCategoryRepository;
use app\common\repositories\system\attachment\AttachmentRepository;
use app\common\repositories\system\CacheRepository;
use app\common\repositories\system\diy\DiyRepository;
use app\common\repositories\system\groupData\GroupDataRepository;
use app\common\repositories\system\groupData\GroupRepository;
use app\common\repositories\system\merchant\MerchantRepository;
use app\common\repositories\system\notice\SystemNoticeConfigRepository;
use app\common\repositories\system\poster\PosterRepository;
use app\common\repositories\user\UserRepository;
use app\common\repositories\user\UserSignRepository;
use app\common\repositories\user\UserVisitRepository;
use app\common\repositories\wechat\TemplateMessageRepository;
use app\common\repositories\wechat\WechatUserRepository;
use crmeb\basic\BaseController;
use crmeb\services\AlipayService;
use crmeb\services\BankService;
use crmeb\services\CopyCommand;
use crmeb\services\ImageWaterMarkService;
use crmeb\services\MiniProgramService;
use crmeb\services\PayService;
use crmeb\services\UploadService;
use crmeb\services\WechatService;
use Exception;
use Joypack\Tencent\Map\Bundle\Location;
use Joypack\Tencent\Map\Bundle\LocationOption;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Log;
use think\Response;

/**
 * Class Common
 * @package app\controller\api
 * @author xaboy
 * @day 2020/5/28
 */
class Common extends BaseController
{
    /**
     * @return mixed
     * @author xaboy
     * @day 2020/5/28
     */
    public function hotKeyword()
    {
        $type = $this->request->param('type');
        switch ($type) {
            case 0:
                $keyword = systemGroupData('hot_keyword');
                break;
            case 1:
                $keyword = systemGroupData('community_hot_keyword');
                break;
        }
        return app('json')->success($keyword);
    }

    public function express(ExpressRepository $repository)
    {
        return app('json')->success($repository->options());
    }

    public function menus()
    {
        return app('json')->success([
            'global_theme' => $this->getThemeVar(systemConfig('global_theme')),
            'banner' => systemGroupData('my_banner'),
            'menu' => systemGroupData('my_menus')
        ]);
    }

    public function refundMessage()
    {
        return app('json')->success(explode("\n", systemConfig('refund_message')));
    }

    private function getThemeVar($type)
    {
        return app()->make(DiyRepository::class)->getThemeVar($type);
    }

    public function advert()
    {
        $config = systemConfig([
            'iosAddress', 'androidAddress', 'appVersion','advert_video_url','advert_bg_url','advert_cover_url','advert_top','advert_bottom',
            'iosMerAddress', 'androidMerAddress', 'appMerVersion','advert_mer_video_url','advert_mer_bg_url','advert_mer_cover_url','advert_mer_top','advert_mer_bottom',

        ]);
        $data = [
            "user"=>[
                "video" => [
                    "url" => $config['advert_video_url'],
                    "poster" => $config['advert_cover_url'],
                    "margionTop" => $config['advert_top'],
                    "marginBottom" => $config['advert_bottom'],
                    "bg_url" => $config['advert_bg_url'],
                ],
                "apk"=>[
                    [
                        "name" => "佰汇生活",
                        "version" => $config['appVersion'],
                        "url" => $config['iosAddress'],
                        "type" => "ios",
                    ],
                    [
                        "name" => "佰汇生活",
                        "version" => $config['appVersion'],
                        "url" => $config['androidAddress'],
                        "type" => "android",
                    ],
                ]
            ],
            "mer"=>[
                "video" => [
                    "url" => $config['advert_mer_video_url'],
                    "poster" => $config['advert_mer_cover_url'],
                    "margionTop" => $config['advert_mer_top'],
                    "marginBottom" => $config['advert_mer_bottom'],
                    "bg_url" => $config['advert_mer_bg_url'],
                ],
                "apk"=>[
                    [
                        "name" => "佰汇生活",
                        "version" => $config['appMerVersion'],
                        "url" => $config['iosMerAddress'],
                        "type" => "ios",
                    ],
                    [
                        "name" => "佰汇生活",
                        "version" => $config['appMerVersion'],
                        "url" => $config['androidMerAddress'],
                        "type" => "android",
                    ],
                ]
            ],
        ];
        return app('json')->success($data);
    }

    public function config()
    {
        $config = Cache::remember('get_api_config',function(){
            $config = systemConfig(['open_update_info', 'store_street_theme', 'is_open_service', 'is_phone_login', 'global_theme', 'integral_status', 'mer_location', 'alipay_open', 'hide_mer_status', 'mer_intention_open', 'share_info', 'share_title', 'share_pic', 'store_user_min_recharge', 'recharge_switch', 'balance_func_status', 'yue_pay_status', 'site_logo', 'routine_logo', 'site_name', 'login_logo', 'procudt_increase_status', 'sys_extension_type', 'member_status', 'copy_command_status', 'community_status','community_reply_status','community_app_switch', 'withdraw_type', 'recommend_switch', 'member_interests_status', 'routine_record_number', 'mer_app_record_number', 'app_record_number', 'beian_sn', 'community_reply_auth','hot_ranking_switch','svip_switch_status','margin_ico','margin_ico_switch','first_avatar_switch','wechat_phone_switch','slide_assembly_switch','community_auth','hsb_open','pay_weixin_open']);
            $cache = app()->make(CacheRepository::class)->search(['copyright_status', 'copyright_context', 'copyright_image', 'sys_intention_agree']);

            if (!isset($cache['sys_intention_agree'])) {
                $cache['sys_intention_agree'] = systemConfig('sys_intention_agree');
            }

            $title = app()->make(UserSignRepository::class)->signConfig();
            if (!$title) {
                $config['member_status'] = 0;
            }
            if (!is_array($config['withdraw_type'])) {
                $config['withdraw_type'] = ['1', '2', '3'];
            }

            $config['tempid'] = app()->make(SystemNoticeConfigRepository::class)->getSubscribe();
            $config['global_theme'] = $this->getThemeVar($config['global_theme']);
//            $config['navigation'] = app()->make(DiyRepository::class)->getNavigation();
            $config = array_merge($config, $cache);
            return $config;
        }, 3600);
        return app('json')->success($config);
    }

    /**
     * @param GroupDataRepository $repository
     * @return mixed
     * @author xaboy
     * @day 2020/6/3
     */
    public function userRechargeQuota(GroupDataRepository $repository)
    {
        $recharge_quota = $repository->groupDataId('user_recharge_quota', 0);
        $recharge_attention = explode("\n", systemConfig('recharge_attention'));
        return app('json')->success(compact('recharge_quota', 'recharge_attention'));
    }

    /**
     * @param $field
     * @return mixed
     * @author xaboy
     * @day 2020/5/28
     */
    public function uploadImage($field)
    {
        $name = $this->request->param('name');
        $to = $this->request->param('to','def');
        $file = $this->request->file($field);
        if (!$file)
            return app('json')->fail('请上传图片');
        if ($name) {
            $f = $this->request->getOriginFile($field);
            if ($f) {
                $f['name'] = $name;
            }
            $this->request->setOriginFile($field, $f);
            $file = $this->request->file($field);
        }
        $file = is_array($file) ? $file[0] : $file;
        if(!in_array($to,['wxfile','receipt'])){
            validate(["$field|图片" => [
                'fileSize' => config('upload.filesize'),
                'fileExt' => 'jpg,jpeg,png,bmp,gif',
                'fileMime' => 'image/jpeg,image/png,image/gif,application/octet-stream'
            ]])->check([$field => $file]);
        }

        $upload = UploadService::create();
        $info = $upload->to($to)->move($field);
        if ($info === false) {
            return app('json')->fail($upload->getError());
        }
        $res = $upload->getUploadInfo();
        $dir = tidy_url($res['dir']);
        return app('json')->success('上传成功', ['path' => $dir,'relative_path' =>$res['dir']]);
    }


    public function uploadCertificate()
    {
        $file = $this->request->file('file');
        if (!$file)
            return app('json')->fail('请上传证书');
        validate(["file|图片" => [
            'fileSize' => config('upload.filesize'),
            'fileExt' => 'jpg,jpeg,png,bmp',
            'fileMime' => 'image/jpeg,image/png',
        ]])->check(['file' => $file]);
        $upload = UploadService::create(1);
        $data = $upload->to('attach')->move('file');
        if ($data === false) {
            return app('json')->fail($upload->getError());
        }
        app()->make(ImageWaterMarkService::class)->run(public_path() . $upload->getFileInfo()->filePath);
        return app('json')->success(['src' => tidy_url($upload->getFileInfo()->filePath)]);
    }

    public function scanUploadImage($field, $token, AttachmentCategoryRepository $repository)
    {
        $id = $this->request->param('pid');
        $merId = $this->request->param('mer_id',0);
        $_merId = Cache::get('scan_mer_'.$token);
        if ($merId != $_merId) return app('json')->fail('商户ID错误，请重新扫码上传');
        $name = $this->request->param('name');
        $file = $this->request->file($field);
        if (!$file)
            return app('json')->fail('请上传图片');
        if ($name) {
            $f = $this->request->getOriginFile($field);
            if ($f) {
                $f['name'] = $name;
            }
            $this->request->setOriginFile($field, $f);
            $file = $this->request->file($field);
        }
        if (!$file)
            return app('json')->fail('请上传图片');
        $file = is_array($file) ? $file[0] : $file;
        if ($id) {
            if (!$category = $repository->get($id, $merId))
                return app('json')->fail('目录不存在');
            $info = [
                'enname' => $category->attachment_category_enname,
                'id' => $category->attachment_category_id
            ];
        } else {
            $info = [
                'enname' => 'def',
                'id' => 0
            ];
        }
        validate(["$field|图片" => [
            'fileSize' => config('upload.filesize'),
            'fileExt' => 'jpg,jpeg,png,bmp,gif',
            'fileMime' => config('upload.image_fileMime'),
        ]])->check([$field => $file]);

        $type = (int)systemConfig('upload_type') ?: 1;
        $upload = UploadService::create($type);
        $data = $upload->to($info['enname'])->move($field);
        if ($data === false) {
            return app('json')->fail($upload->getError());
        }
        $res = $upload->getUploadInfo();
        $res['dir'] = tidy_url($res['dir']);
        $_name = '.' . $file->getOriginalExtension();
        $data = [
            'attachment_category_id' => $info['id'],
            'attachment_name' => str_replace($_name, '', $file->getOriginalName()),
            'attachment_src' => $res['dir']
        ];
        $attach = app()->make(AttachmentRepository::class)->create((int)$type, (int)$merId, 0, $data);
        Cache::sadd('scan_'.$token,$attach->attachment_id);
        return app('json')->success(['src' => $data['attachment_src']]);
    }


    /**
     * @return Response
     * @author xaboy
     * @day 2020/6/3
     */
    public function wechatNotify()
    {
        try {
            if($this->request->header('content-type') === 'application/json'){
                return response(WechatService::create()->handleNotifyV3()->getContent());
            }
            return response(WechatService::create()->handleNotify()->getContent());
        } catch (Exception $e) {
            Log::info('支付回调失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
    }


    /**
     * @return bool|void|null
     * @author: fupeng
     * @day: 2023/10/7
     */
    public function BankPayNotify()
    {
        $data = $this->request->param();
        try {
            Log::info('hsb支付回调:' . var_export($data, true));
            return (new BankService())->bankCallBack($data);
        } catch (Exception $e) {
            Log::info('hsb支付回调失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
    }

    public function BankRefundNotify()
    {
        $data = $this->request->param();
        try {
            Log::record(['msg12'=>'惠市宝退款回调222','data'=>$data]);
//            return (new BankService())->bankRefundCallBack($data);
        } catch (Exception $e) {
            Log::info('惠市宝退款回调失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
    }


    /**
     * @return mixed
     * @author: fupeng
     * @day: 2023/11/20
     * hsb_获取支付结果
     */
    public function gatherEnquireOrder()
    {
        $where = $this->request->param();
        $data = (new BankService())->gatherEnquireOrder($where['order_id']);
        if(isset($where['is_bug'])){
            var_dump($data);
            return 0;
        }
        try {
            if(isset($data['Ordr_Stcd']) && $data['Ordr_Stcd'] == "2"){

                    $data['order_sn'] = $data['Main_Ordr_No'];
                    $config = systemConfig(['hsb_open']);

                    $is_combine = 0;
                     $sub_arr = [];
                    if ($config['hsb_open'] && $config['hsb_open'] =='1') {
                        $is_combine =1;

                        if(isset($data['Orderlist'])){
                            foreach ($data['Orderlist'] as $v){
                                $sub_arr[]=[
                                    'transaction_id'=> $v['Sub_Ordr_Id'],
                                    'out_trade_no'=> $v['Cmdty_Ordr_No']
                                ];
                            }
                        }else{
                            $sub_arr[] = [
                                    'transaction_id'=> $data['Prim_Ordr_No'],
                                    'out_trade_no'=> $data['Main_Ordr_No']
                            ];
                        }

                        $data['sub_orders'] =$sub_arr;

                    }
//                    var_dump($data);
                     event('pay_success_order', ['order_sn' => $data['order_sn'], 'data' => $data, 'is_combine' => $is_combine]);
                return app('json')->success();
            }else{
                Log::info('hsb支付失败结果:' . $data['Ordr_Stcd']);
            }

        } catch (\Exception $e) {
            Log::info('hsb支付结果查询:' . $e->getMessage());
            return app('json')->fail($e->getMessage());
        }


    }


    public function httpcurl($url, $params = false, $post = false, $https = false){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($post === true) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params === false) {
                curl_setopt($ch, CURLOPT_URL, $url);
            } else {
                if (is_array($params)) {
                    $params = http_build_query($params);
                }
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            }
        }

        if ($https === true) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        }
        $response = curl_exec($ch);
        // if ($response === false) {
        //     Illuminate\Support\Facades\Log::error(sprintf('curl 错误。 url:%s, error:%s', $url, curl_error($ch)));
        //     return false;
        // }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }


    public function bankUploadFile()
    {
        Log::info('hsb对账单文件推送地址:');
//        $file = $this->request->file('jetbra_zip');

//        $dstPath = '/www/wwwroot/test.shop.baihuitimes.com/public/uploads/hsb';
////        file_put_contents($dstPath,file_get_contents('php://input'),true);
////        return ['msg'=>'ok'];
//        $file = $this->request->file('jetbra_zip');
////        Log::record(['msg12'=>'hsb推送2','data'=>$file]);
//        if (!$file) return app('json')->fail('请上传文件');
//
//        $file->move($dstPath, '123.zip');


        $array= $this->request->file();
        $field =  array_key_first($array);
        if (!$field)
            return app('json')->fail('请上传文件');
        $upload = UploadService::create(1);
        $data = $upload->to('hsb')->move($field);
        if ($data === false) {
            return app('json')->fail($upload->getError());
        }
        return app('json')->success(['src' => tidy_url($upload->getFileInfo()->filePath)]);
    }

    /**
     * 电商收付通合并支付回调
     */
    public function wechatCombinePayNotify($type)
    {
        if (!in_array($type, ['order', 'presell'], true))
            throw new ValidateException('参数错误');
        try {
            return WechatService::create()->handleCombinePayNotify($type);
        } catch (Exception $e) {
            Log::info('电商收付通支付回调失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
    }

    /**
     * 电商收付通合并支付回调
     */
    public function routineCombinePayNotify($type)
    {
        if (!in_array($type, ['order', 'presell'], true))
            throw new ValidateException('参数错误');
        try {
            return WechatService::create()->handleCombinePayNotify($type);
        } catch (Exception $e) {
            Log::info('小程序电商收付通支付回调失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
    }

    public function routineNotify()
    {
        try {
            Log::info('支付回调header:' . var_export([$this->request->header()], true));
            if($this->request->header('content-type') === 'application/json'){
                return response(MiniProgramService::create()->handleNotifyV3()->getContent());
            }
            return response(MiniProgramService::create()->handleNotify()->getContent());
        } catch (Exception $e) {
            Log::info('支付回调失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine(),$this->request->header()], true));
        }
    }

    public function alipayNotify($type)
    {
        if (!in_array($type, ['order', 'user_recharge', 'presell', 'user_order'], true))
            throw new ValidateException('参数错误');
        $post = $_POST;
        $get = $_GET;
        $_POST = $this->request->post();
        $_GET = $this->request->get();
        try {
            AlipayService::create()->notify($type);
        } catch (Exception $e) {
            Log::info('支付宝回调失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        } finally {
            $_POST = $post;
            $_GET = $get;
        }
    }

    public function getVersion()
    {
        return app('json')->success(['version' => get_crmeb_version(), 'host' => request()->host(), 'system' => PHP_OS, 'php' => @phpversion()]);
    }

    /**
     * 获取图片base64
     * @return mixed
     */
    public function get_image_base64()
    {
        list($imageUrl, $codeUrl) = $this->request->params([
            ['image', ''],
            ['code', ''],
        ], true);
        checkSuffix([$imageUrl, $codeUrl]);
        try {
            $codeTmp = $code = $codeUrl ? image_to_base64($codeUrl) : '';
            if (!$codeTmp) {
                $putCodeUrl = put_image($codeUrl);
                $code = $putCodeUrl ? image_to_base64('./runtime/temp' . $putCodeUrl) : '';
                $code && unlink('./runtime/temp' . $putCodeUrl);
            }

            $imageTmp = $image = $imageUrl ? image_to_base64($imageUrl) : '';
            if (!$imageTmp) {
                $putImageUrl = put_image($imageUrl);
                $image = $putImageUrl ? image_to_base64('./runtime/temp' . $putImageUrl) : '';
                $image && unlink('./runtime/temp' . $putImageUrl);
            }
            return app('json')->success(compact('code', 'image'));
        } catch (Exception $e) {
            return app('json')->fail($e->getMessage());
        }
    }

    public function home()
    {
        $banner = systemGroupData('home_banner', 1, 10);
        $menu = systemGroupData('home_menu');
        $hot = systemGroupData('home_hot', 1, 4);
        $activity = systemGroupData('sys_activity', 1, 1)[0] ?? null;
        $activity_lst = systemGroupData('sys_activity', 1, 3);
        $ad = systemConfig(['home_ad_pic', 'home_ad_url']);
        $category = app()->make(StoreCategoryRepository::class)->getTwoLevel();
        return app('json')->success(compact('banner', 'menu', 'hot', 'ad','activity', 'activity_lst','category'));
    }

    public function activityLst($id)
    {
        $merId = (int)$id;
        [$page, $limit] = $this->getPage();
        return app('json')->success($merId ? merchantGroupData($merId, 'mer_activity', $page, $limit) : systemGroupData('sys_activity', $page, $limit));
    }

    public function activityInfo($id)
    {
        $activity = app()->make(GroupDataRepository::class)->getData((int)$id,1);
        if (!$activity) {
            return app('json')->fail('活动不存在');
        }
        $activity['merchant'] = $activity['group_mer_id'] ? app()->make(MerchantRepository::class)->search(['mer_id' => $activity['group_mer_id']])->field('mer_name,mer_avatar')->find() : null;
        return app('json')->success($activity);
    }

    public function visit()
    {
        if (!$this->request->isLogin()) return app('json')->success();
        [$page, $type] = $this->request->params(['page', 'type'], true);
        $uid = $this->request->uid();
        if (!$page || !$uid) return app('json')->fail();
        $userVisitRepository = app()->make(UserVisitRepository::class);
        $type == 'routine' ? $userVisitRepository->visitSmallProgram($uid, $page) : $userVisitRepository->visitPage($uid, $page);
        return app('json')->success();
    }

    public function hotBanner($type)
    {
        if (!in_array($type, ['new', 'hot', 'best', 'good']))
            $data = [];
        else
            $data = systemGroupData($type . '_home_banner');
        return app('json')->success($data);
    }

    public function pay_key($key)
    {
        $cache = Cache::store('file');
        if (!$cache->has('pay_key' . $key)) {
            return app('json')->fail('支付链接不存在');
        }
        return app('json')->success($cache->get('pay_key' . $key));
    }

    public function lbs_geocoder()
    {
        $data = explode(',', $this->request->param('location', ''));
        $locationOption = new LocationOption(systemConfig('tx_map_key'));
        $locationOption->setLocation($data[0] ?? '', $data[1] ?? '');
        $location = new Location($locationOption);
        $res = $location->request();
        if ($res->error) {
            return app('json')->fail($res->error);
        }
        if ($res->status) {
            return app('json')->fail($res->message);
        }
        if (!$res->result) {
            return app('json')->fail('获取失败');
        }
        return app('json')->success($res->result);
    }


    public function getCommand()
    {
        $key = $this->request->param('key');
        if (!preg_match('/^(\/@[1-9]{1}).*\*\//', $key)) {
            return app('json')->fail('无效口令');
        }
        $userInfo = $this->request->isLogin() ? $this->request->userInfo() : null;
        $command = app()->make(CopyCommand::class)->getMassage($key);
        if (empty($command)) return app('json')->fail('无效口令');
        $info = [];
        if ($command['uid']) {
            $user = app()->make(UserRepository::class)->get($command['uid']);
            $info = [
                'uid' => $user['uid'],
                'nickname' => $user['nickname'],
                'avatar' => $user['avatar'],
            ];
        }
        switch ($command['type']) {
            case 0:
                $data = app()->make(ProductRepository::class)->detail($command['id'], $userInfo);
                $ret['product_id'] = $command['id'];
                break;
            case 1:
                $data = app()->make(ProductRepository::class)->detail($command['id'], $userInfo);
                $ret['product_id'] = $command['id'];
                break;
            case 2:
                $data = app()->make(ProductPresellRepository::class)->apiDetail((int)$command['id'], $userInfo);
                $ret['activity_id'] = $command['id'];
                break;
            case 4:
                $data = app()->make(ProductGroupRepository::class)->apiDetail($command['id'], $userInfo);
                $ret['activity_id'] = $command['id'];
                break;
            case 30:
                $data = app()->make(ProductAssistSetRepository::class)->detail($command['id'], $userInfo);
                $ret['activity_id'] = $command['id'];
                break;
            case 40:
                $data = app()->make(ProductGroupBuyingRepository::class)->detail($command['id'], $userInfo);
                $ret['activity_id'] = $command['id'];
                break;
        }
        if ($userInfo && $command['uid']) app()->make(UserRepository::class)->bindSpread($userInfo, $command['uid']);
        $ret['product_type'] = $command['type'];
        $ret['user'] = $info;
        $ret['com'] = $command['com'];
        $ret['data'] = $data;
        return app('json')->success($ret);
    }

    public function script()
    {
        return \response(systemConfig('static_script'));
    }

    public function appVersion()
    {
        return app('json')->success(systemConfig([
            'appVersion',
            'iosAddress',
            'androidAddress',
            'openUpgrade'
        ]));
    }

    public function appMerVersion()
    {
        return app('json')->success(systemConfig([
            'appMerVersion',
            'iosMerAddress',
            'androidMerAddress',
            'openMerUpgrade'
        ]));
    }

    public function deliveryNotify()
    {
        try {
            //return app('json')->success();
            $params = $this->request->param();
            app()->make(DeliveryOrderRepository::class)->notify($params);

            if(isset($params['sf_order_id'])){
                return json_encode([
                    "error_code" => 0,
                    "error_msg"=> "success"
                ]);
            }
        } catch (Exception $e) {
            Log::info('同城配送订单回调失败:' . var_export([$e->getMessage(), $e->getFile() . ':' . $e->getLine()], true));
        }
    }

    public function diy()
    {
        $merId = $this->request->param('id', 0);
        $id = $this->request->param('did', 0);
        $version = $this->request->param('version', 0);
        $data = app()->make(DiyRepository::class)->show($merId, $id, 1);
        if($version){
            return app('json')->encode($data);
        }
        return app('json')->success($data['data']);
    }

    public function getNavigation()
    {
        return app('json')->success(app()->make(DiyRepository::class)->getNavigation());
    }

    public function micro()
    {
        $version = $this->request->param('version', 0);
        $id = $this->request->param('id', 0);
        $data = Cache::remember('sys.get_sys_micro_'.$id,function()use($id){
            $data = app()->make(DiyRepository::class)->getMicro($id);
            return json_encode($data, JSON_UNESCAPED_UNICODE);
        }, 3600);
        $data = json_decode($data, true);
        if($version){
            return app('json')->encode($data);
        }
        return app('json')->success($data['data']);
    }

    /**
     * 是否关注
     * @return mixed
     */
    public function subscribe()
    {
        if ($this->request->isLogin()) {
            $user = $this->request->userInfo();
            if ($user && $user['wechat_user_id']) {
                $wechatUserService = app()->make(WechatUserRepository::class);
                $subscribe = $wechatUserService->getWhereCount([
                        'wechat_user_id' => $user['wechat_user_id'],
                        'subscribe' => 1
                    ]) > 0;
                return app('json')->success(['subscribe' => $subscribe]);
            }
        }
        return app('json')->success(['subscribe' => false, 'qrcode' => systemConfig('wechat_qrcode')]);
    }

    public function open_screen()
    {
        $key = ['open_screen_advertising'];
        $group = app()->make(GroupRepository::class)->getSearch([])->where('group_key','in',$key)->find();
        $data= app()->make(GroupDataRepository::class)->getGroupDataLst($this->request->merId(),$group->group_id,1, 10);
        $data['config'] = systemConfig(['open_screen_switch','open_screen_time','open_screen_space']);
        return app('json')->success($data);
    }

    /**
     * @return mixed
     * @author: fupeng
     * @day: 2023/11/30
     * 获取商家海报列表
     */
    public function posterLst()
    {
        [$page, $limit] = $this->getPage();
        return app('json')->success(app()->make(PosterRepository::class)->getList([],$page, $limit));
    }


    public function kuaidi()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isPost()) {
            $kuaidi = (new StoreOrderExpress());
            $post = $this->request->post();
            $param = json_decode($post["param"], true);
            \think\facade\Log::record([
                'msg'=>'8888888','past'=>$post,
                'data'=>json_encode($param['lastResult']['data']),
                'data2'=>$param]);
            // 接收消息
            try {

                $status = $param['status']; // 状态 polling:监控中，shutdown:结束，abort:中止，updateall：重新推送
                $message = $param['lastResult']['message']; // 消息体
                $state = $param['lastResult']['state']; // 快递单当前状态，包括0在途，1揽收，2疑难，3签收，4退签，5派件，6退回，7转投
                $ischeck = $param['lastResult']['ischeck']; // 是否签收标记
                $nu = $param['lastResult']['nu']; // 快递单号
                $com = $param['lastResult']['com']; // 快递公司编码
                $data = $param['lastResult']['data']; // 数组，包含多个对象，每个对象字段如展开所示
                // 查询快递是否存在
                $express = $kuaidi->where(['express_no' => $nu])->find();
                if($express){
                    // 判断来源
                    if($post["sign"] != strtoupper(md5($post["param"].$express['sign']))){
                        return json(["result" => false, "returnCode" => "405", "message" => "校验码错误"]);
                    }
                    // 更新数据
                    $express->message = $message;
                    $express->status = $status;
                    $express->state = $state;
                    $express->ischeck = $ischeck;
                    $express->com = $com;
                    $express->express_content = json_encode($data);
                    $express->save();
                    // 判断更新状态
                    if($express){
                        return json(["result" => true, "returnCode" => "200", "message" => "接收成功"]);

                    }
                }else{
                    return json(["result" => false, "returnCode" => "404", "message" => "快递单号不存在"]);
                }
            } catch (Exception $e) {
                return json(["result" => false, "returnCode" => "500", "message" => "服务器错误"]);
            }
        }
        return json(["result" => false, "returnCode" => "500", "message" => "非正常访问"]);
    }
}
